package alice.exercise.leetcode.difficult;

import java.util.*;

/**
 * TODO 1032. 字符流
 *
 * @author Alice
 * @since 2023-03-24 星期五 9:39
 */
public class StreamChecker {
  private final Map<Integer, Set<String>> map;
  private final Set<String>[] dict;
  private final List<Character> list;
  private final StringBuilder builder;

  public StreamChecker(String[] words) {
    builder = new StringBuilder();
    dict = new Set[26];
    map = new TreeMap<>();
    list = new ArrayList<>();
    int length, dictIndex;
    for (String word : words) {
      length = word.length();
      dictIndex = word.charAt(length - 1) - 'a';
      if (dict[dictIndex] == null) {
        dict[dictIndex] = new HashSet<>();
      }
      dict[dictIndex].add(word);

      Set<String> strings = map.get(length);
      if (strings == null) {
        strings = new HashSet<>();
      }
      strings.add(word);
      map.put(length, strings);
    }
  }

  public boolean query(char letter) {
    builder.append(letter);
    Set<String> possible = dict[letter - 'a'];
    if (possible == null) {
      return false;
    }
    return possible.parallelStream().anyMatch(s -> builder.toString().endsWith(s));
  }

  private boolean reserveEquals(String s1, String s2) {
    int n = s1.length();
    for (int i = 0; i < n; i++) {
      if (s1.charAt(i) != s2.charAt(n - i - 1)) {
        return false;
      }
    }
    return true;
  }
}
